<?php
namespace app\serverexchangerate\logic;

use \app\manage\logic\BaseLogic;

/**
 * @author:      李颖
 * @DateTime:    2017-09-12 10:17:09
 * @Description: 汇率
 */
class Exchangerate extends BaseLogic
{
	protected $name = 'exchangerate';
    protected $config = 'db_config_exchangerate';
    protected $exchangerateModel = 'app\serverexchangerate\model\Exchangerate';


    /*添加一条汇率记录表*/
    public function addRate($data): array 
    {
    	$data['millisecond'] = get_millisecond();
    	$res = $this->model($this->exchangerateModel)->save($data);
    	return auto_return($res, '添加成功');
    }

    /*修改一条汇率记录*/
    public function updateRate($data): array 
    {
    	$_where['id'] = $data['id'];
    	$_where['status'] = 1;
    	$rateInfo = $this->model($this->exchangerateModel)->where($_where)->find();
    	if(!$rateInfo){
    		return verify_err(null, '没有该条记录');
    	}
    	//对价格进行验证
    	$max_price = $data['max_price'] ?? $rateInfo['max_price'];
    	$min_price = $data['min_price'] ?? $rateInfo['min_price'];
    	$open_price = $data['open_price'] ?? $rateInfo['open_price'];
    	$close_price = $data['close_price'] ?? $rateInfo['close_price'];
    	$now_price = $data['now_price'] ?? $rateInfo['now_price'];
    	if($max_price < $min_price){	return verify_err(null, '最高价不能小于最低价');	}
    	if($open_price < $min_price || $open_price > $max_price){ return verify_err(null, '开盘价应在最低最高价之间'); }
    	if($close_price < $min_price || $close_price > $max_price){ return verify_err(null, '收盘价应在最低最高价之间'); }
    	if($now_price < $min_price || $now_price > $max_price){ return verify_err(null, '当前价应在最低最高价之间'); }

    	$res = $this->model($this->exchangerateModel)->save($data, $_where);
    	return auto_return($res, '修改成功');
    }

    /*获取汇率记录列表（分页）*/
    public function rateList($data): array 
    {
    	$_where['status'] = 1;
    	$res = $this->model($this->exchangerateModel)
                    ->where($_where)
                    ->order('id desc')
                    ->paginate($data['listRows'], false, ['page'=>$data['page']])
                    ->toArray(); 
        return auto_return_page($res, '已找到汇率记录列表数据', '没有汇率记录列表数据');
    }

    /*获取最新一条汇率记录*/
    public function oneNewRate(): array 
    {
    	$_where['status'] = 1;
    	$res = $this->model($this->exchangerateModel)->where($_where)->order('id desc')->find();
    	return auto_return($res);
    }

    /*删除一条汇率记录*/
    public function delOneRate($data): array 
    {
    	$_where['id'] = $data['id'];
    	$_where['status'] = 1;
    	$res = $this->model($this->exchangerateModel)->where($_where)->delete();
    	return auto_return($res, '已删除该条记录');
    }



}